package cn.w.outdoor.lib.common;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class SingleThreadPoll {

    private final static SingleThreadPoll ourInstance = new SingleThreadPoll();

    public static SingleThreadPoll getInstance() {
        return ourInstance;
    }

    private SingleThreadPoll() {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                release();
            }
        });
    }

    private final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();

    public void executeSingle(Runnable runnable) {
        singleThreadExecutor.execute(runnable);
    }

    public <T> Future<T> submitSingle(Runnable task, T result) {
        return singleThreadExecutor.submit(task, result);
    }

    public Future<?> submitSingle(Runnable task) {
        return singleThreadExecutor.submit(task);
    }

    public <T> Future<T> submitSingle(Callable<T> task) {
        return singleThreadExecutor.submit(task);
    }

    private void release() {
        singleThreadExecutor.shutdownNow();
    }

}
